<template>
  <el-dialog
    width="45%"
    :visible.sync="scheduleVisible"
    @closed="scheduleclose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <template slot="title">
      <div class="titleZise">
        <div>{{ form.scheduleId != null ? "编辑" : "新增" }}</div>
        <el-radio-group
          @change="scheduleclose('change')"
          v-model="radio"
          :disabled="form.scheduleId != null"
        >
          <el-radio-button label="日程"></el-radio-button>
          <el-radio-button label="任务"></el-radio-button>
        </el-radio-group>
      </div>
    </template>
    <el-form
      :model="form"
      status-icon
      :rules="scheduleRules"
      ref="form"
      label-width="120px"
      size="medium"
    >
      <el-form-item :hidden="radio == '任务'" prop="scheduleType" label="日程类型">
        <el-select v-model="form.scheduleType" placeholder="请选择">
          <el-option
            v-for="item in scheduleoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="scheduleTitle" label="标题">
        <el-input v-model="form.scheduleTitle" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="adrress" label="地址">
        <el-input v-model="form.adrress" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="起止时间">
        <el-date-picker
          v-model="operTimes"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['09:00:00', '18:00:00']"
        ></el-date-picker>
        <el-form-item hidden prop="isRepeat">
          <el-checkbox @change="repeat" v-model="form.isRepeat">重复</el-checkbox>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-row v-if="form.isRepeat">
          <el-col :span="5">重复类型：</el-col>
          <el-col :span="6">
            <el-form-item prop="repeatType">
              <el-select @change="repeatType" v-model="form.repeatType" placeholder="请选择">
                <el-option
                  v-for="item in repeatoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.repeatType == 'weeks'" style="margin-top: 15px">
          <el-col :span="5">重复频率(周)：</el-col>
          <el-checkbox-group v-model="repeatWeek">
            <el-checkbox
              v-for="week in weekoptions"
              :label="week.value"
              :key="week.value"
            >{{ week.label }}</el-checkbox>
          </el-checkbox-group>
        </el-row>
        <el-row v-if="form.repeatType == 'customCycle'" style="margin-top: 15px">
          <el-col :span="5">重复频率(天)：</el-col>
          <el-col :span="6">
            <el-form-item prop="repeatTimes">
              <el-input-number size="mini" v-model="form.repeatTimes" :min="1" :max="10"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.isRepeat && form.repeatType != 'weeks'" style="margin-top: 15px">
          <el-col :span="5">结束条件：</el-col>
          <el-col :span="6">
            <el-form-item prop="repeatEndType">
              <el-select @change="repeatEndType" v-model="form.repeatEndType" placeholder="请选择">
                <el-option
                  v-for="item in repeatEndoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.repeatEndType == 'finish'" :span="6" :offset="2">
            <el-form-item prop="repeatEndDate">
              <!-- <el-date-picker v-model="form.repeatEndDate" type="date" placeholder="选择日期"></el-date-picker> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.repeatType == 'weeks'" style="margin-top: 15px">
          <el-col :span="4">重复开始日期：</el-col>
          <el-col :span="8">
            <el-form-item prop="repeatStarDate">
              <!-- <el-date-picker v-model="form.repeatStarDate" type="date" placeholder="选择日期"></el-date-picker> -->
            </el-form-item>
          </el-col>
          <el-col :span="4">重复结束日期：</el-col>
          <el-col :span="8">
            <el-form-item prop="repeatEndDate">
              <!-- <el-date-picker v-model="form.repeatEndDate" type="date" placeholder="选择日期"></el-date-picker> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item prop="startWarnType" label="开始提醒">
        <el-select v-model="form.startWarnType" placeholder="请选择">
          <el-option
            v-for="item in WarnTypeoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="endWarnType" label="截止提醒">
        <el-select v-model="form.endWarnType" placeholder="请选择">
          <el-option
            v-for="item in WarnTypeoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-for="(domain, index) in functionary" :label="'参与人员'" :key="domain.key">
        <el-row>
          <el-col :span="6">
            <el-select v-model="domain.userType" placeholder="请选择人员类型">
              <el-option
                v-for="item in userTypeoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="15" :offset="1">
            <el-select v-model="domain.userName" multiple filterable placeholder="请输入关键词">
              <el-option
                v-for="item in users"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="1" :offset="1">
            <i v-if="index >= 1" class="el-icon-error" @click.prevent="removeDomain(domain)"></i>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="addDomain">添加人员</el-button>
      </el-form-item>
      <el-form-item label="关联业务">
        <el-row>
          <el-col :span="8">
            <el-form-item prop="dataType">
              <el-select @change="selectdataTy" v-model="form.dataType" placeholder="请选择">
                <el-option
                  v-for="item in dataTypeoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="15" :offset="1">
            <el-form-item prop="dataKey">
              <el-select
                v-model="form.dataKey"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteContract"
                :loading="contractLoading"
              >
                <el-option
                  v-for="item in contractOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item prop="memo" label="详细描述">
        <el-input
          type="textarea"
          maxlength="500"
          :autosize="{ minRows: 4, maxRows: 8 }"
          placeholder="填写该任务更详细的描述(0/500字)"
          v-model="form.memo"
        ></el-input>
      </el-form-item>
      <el-form-item :hidden="radio == '日程'" prop="taskStatus" label="任务完成情况">
        <el-select v-model="form.taskStatus" placeholder="请选择">
          <el-option
            v-for="item in taskStatusoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-row>
          <el-col :span="24">
            <qm-file-upload
              :dataKey="form.scheduleId"
              :editable="true"
              title="附件上传"
              fileSize="20"
              fileType=".jpg,.png,.doc,.docx,.xls,.xlsx,.pdf,.txt,.zip,.rar"
              @uploaded="uploadSuccess"
            ></qm-file-upload>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="fCancel">取 消</el-button>
      <el-button type="primary" @click="submitSchedule('form')">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 组件
import QmFileUpload from "@/libs/components/qm-file-upload";
import request from "@/utils/request";

import _ from "lodash";
export default {
  data() {
    return {
      WarnTypeoptions: [
        {
          value: "noWarn",
          label: "不提醒",
        },
        {
          value: "punctuality",
          label: "准时",
        },
        {
          value: "fiveMinutes",
          label: "提前5分钟",
        },
        {
          value: "tenMinutes",
          label: "提前10分钟",
        },
        {
          value: "thirtyMinutes",
          label: "提前30分钟",
        },
        {
          value: "oneHours",
          label: "提前1小时",
        },
        {
          value: "twoHours",
          label: "提前2小时",
        },
        {
          value: "sixHours",
          label: "提前6小时",
        },
        {
          value: "oneDay",
          label: "提前1天",
        },
        {
          value: "twoDay",
          label: "提前2天",
        },
      ],
      weekoptions: [
        { value: 1, label: "每周一" },
        { value: 2, label: "每周二" },
        { value: 3, label: "每周三" },
        { value: 4, label: "每周四" },
        { value: 5, label: "每周五" },
        { value: 6, label: "每周六" },
        { value: 0, label: "每周日" },
      ],
      scheduleoptions: [
        {
          value: "visitingClients",
          label: "拜访客户",
        },
        {
          value: "conference",
          label: "会议",
        },
        {
          value: "rest",
          label: "其他",
        },
      ],
      taskStatusoptions: [
        {
          value: "finished",
          label: "已完成",
        },
        {
          value: "unfinished",
          label: "未完成",
        },
        {
          value: "postpone",
          label: "推迟",
        },
      ],
      //关联项目下拉框数据
      contractOptions: [],
      userTypeoptions: [
        {
          value: "principal",
          label: "负责人",
        },
        {
          value: "participant",
          label: "参与人",
        },
      ],
      repeatEndoptions: [
        {
          value: "never",
          label: "永不结束",
        },
        {
          value: "finish",
          label: "结束日期",
        },
      ],
      repeatoptions: [
        {
          value: "everyday",
          label: "每天",
        },
        {
          value: "everyTuesday",
          label: "每周二",
        },
        {
          value: "every30",
          label: "每月30日",
        },
        {
          value: "weeks",
          label: "周(勿跨天)",
        },
        {
          value: "customCycle",
          label: "自定义周期",
        },
      ],
      dataTypeoptions: [
        {
          value: "customer",
          label: "客户",
        },
        {
          value: "chance",
          label: "商机",
        },
        {
          value: "contract",
          label: "合同",
        },
        {
          value: "project",
          label: "项目",
        },
      ],
      // 规则
      scheduleRules: {
        scheduleTitle: [
          { required: true, message: "请填写标题", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在1-50 个字符以内",
            trigger: "blur",
          },
        ],
        adrress: [
          { required: true, message: "请填写地址", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在1-50 个字符以内",
            trigger: "blur",
          },
        ],
        //日程类别
        scheduleType: [
          { required: true, message: "请选择日程类型", trigger: "change" },
        ],
        startWarnType: [
          {
            required: true,
            message: "请选择开始提醒类型",
            trigger: "change",
          },
        ],
        endWarnType: [
          {
            required: true,
            message: "请选择结束提醒类型",
            trigger: "change",
          },
        ],
        memo: [
          { required: true, message: "请填写详细描述", trigger: "blur" },
          {
            min: 1,
            max: 500,
            message: "长度在1-500 个字符以内",
            trigger: "blur",
          },
        ],
        //任务完成情况
        taskStatus: [
          {
            required: true,
            message: "请选择任务完成情况",
            trigger: "change",
          },
        ],
      },
      //负责人员
      functionary: [
        {
          userType: null,
          userName: [],
        },
      ],
      form: {
        parentId: "",
        scheduleType: "",
        scheduleTitle: "",
        adrress: "",
        startTime: "",
        endTime: "",
        isRepeat: null,
        repeatType: "",
        repeatTimes: "",
        repeatWeeks: "",
        repeatEndType: "",
        repeatStarDate: "",
        repeatEndDate: "",
        startWarnType: "",
        endWarnType: "",
        dataType: "",
        dataKey: "",
        dataTitle: "",
        memo: "",
        taskFinishType: "",
        taskStatus: "",
        scheduleId: null,
        //附件id
        attachmentIds: null,
      },
      // 下拉框数据
      users: null,
      contractLoading: false,
      //日程
      scheduleVisible: false,
      //radio按钮
      radio: "日程",
      operTimes: [],
    };
  },
  components: {
    QmFileUpload,
  },
  props: {
    model: {
      type: Object,
      default() {
        return {};
      },
    },
    scheduleVisiblePreve: {
      type: Boolean,
      default: false,
    },
    formPrev: {
      type: Object,
      default() {
        return null;
      },
    },
    functionaryPrev: {
      type: Array,
      default() {
        return null;
      },
    },
    time: {
      type: Array,
      default() {
        return [];
      },
    },
    radioVal: {
      type: String,
      default: null,
    },
  },
  watch: {
    radioVal: {
      handler(value) {
        if (!value) return;
        this.radio = value;
      },
      immediate: true,
    },
    time: {
      handler(value) {
        if (!value) return;
        this.operTimes = value;
      },
      immediate: true,
    },
    scheduleVisiblePreve: {
      handler(value) {
        if (!value) return;
        this.scheduleVisible = value;
      },
      immediate: true,
    },
    formPrev: {
      handler(value) {
        if (!value) return;
        this.form = _.cloneDeep(value);
        // 初始化时间
        this.operTimes = [value.startTime, value.endTime];
        //初始化关联数据
        let dataKey = this.form.dataKey;
        //关联人员
        if (this.form.dataType != "") {
          this.selectdataTy(this.form.dataType);
          this.form.dataKey = dataKey;
        }
      },
      deep: true,
    },
    functionaryPrev: {
      handler(value) {
        if (!value) return;
        this.functionary = _.cloneDeep(value);
      },
      deep: true,
    },
  },
  created() {
    this.remoteMethod();
  },
  methods: {
    // 请求下拉框数据
    remoteMethod() {
      request({
        url: "/admin/scheduleTask/userSelect2",
        method: "get",
      })
        .then((r) => {
          if (r && !r.initMessage) {
            this.users = r.data.map((m) => {
              return {
                value: m.userId,
                label: m.userName,
              };
            });
          } else {
            this.$message.error(r.initMessage || "数据请求失败");
          }
        })
        .catch((e) => {
          this.$message.error(e);
        });
    },
    // 状态改变时触发的事件
    repeatEndType(value) {
      if (value == "never") {
        this.form.repeatEndDate = "";
      }
    },
    repeatType(value) {
      if (value != "customCycle") {
        this.form.repeatTimes = "";
      }
    },
    //重复
    repeat(value) {
      if (value) {
        this.form.repeatType = this.repeatoptions[0].value;
        this.form.repeatEndType = this.repeatEndoptions[0].value;
      } else {
        this.form.repeatType = "";
        this.form.repeatTimes = "";
        this.form.repeatEndType = "";
        this.form.repeatEndDate = "";
      }
    },
    // 新增提交
    submitSchedule(formName) {
      if (this.radio == "日程") {
        this.form.taskStatus = "暂无";
      } else {
        this.form.scheduleType = "task";
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.operTimes.length > 1) {
            let postModel = _.extend({}, this.form);
            //将时间进行赋值
            postModel.startTime = formatter.formatDateTime(this.operTimes[0]);
            postModel.endTime = formatter.formatDateTime(this.operTimes[1]);
            postModel.repeatEndDate = formatter.formatDateTime(
              postModel.repeatEndDate
            );
            postModel.repeatStarDate = formatter.formatDateTime(
              postModel.repeatStarDate
            );
            //关联title
            if (postModel.dataKey != null) {
              this.contractOptions.forEach((item) => {
                if (item.value == postModel.dataKey) {
                  postModel.dataTitle = item.label;
                  return false;
                }
              });
            }
            postModel.isRepeat = postModel.isRepeat ? "1" : "0";
            //重复为周重组
            if (postModel.repeatType == "weeks") {
              postModel.repeatWeeks = this.repeatWeek.toString();
            } else {
              postModel.repeatWeeks = null;
            }
            //创建人、参与人
            let newFunctionary = [];
            this.functionary.forEach((item) => {
              if (item.userType != null) {
                item.userName.forEach((user) => {
                  newFunctionary.push({
                    userId: user,
                    userType: item.userType,
                  });
                });
              }
            });
            if (postModel.scheduleId != null) {
              request({
                url: "/admin/scheduleTask/editScheduleTask",
                method: "post",
                data: {
                  scheduleTask: postModel,
                  functionary: newFunctionary,
                },
              })
                .then((r) => {
                  if (r.success && !r.initMessage) {
                    // 通知父组件状态为false
                    this.$emit("fSubmit", {
                      data: r.parameters.scheduleTask,
                      action: "edit",
                    });
                    this.scheduleVisible = false;
                    this.$message({
                      type: "success",
                      message: "修改成功!",
                    });
                    // 更新任务栏信息
                    // 通知父组件更新
                    this.$emit("handleClick");
                  } else {
                    this.$message.error(r.initMessage || "数据请求失败");
                  }
                })
                .catch((e) => {
                  this.$message.error(e);
                });
            } else {
              request({
                url: "/admin/scheduleTask/addScheduleTask",
                method: "post",
                data: {
                  scheduleTask: postModel,
                  functionary: newFunctionary,
                  attachmentIds: postModel.attachmentIds,
                  radio: this.radio,
                },
              })
                .then((r) => {
                  if (r && !r.initMessage) {
                    // 关闭弹窗
                    this.scheduleVisible = false;
                    // 通知父组件状态为false
                    this.$emit("fSubmit", {
                      data: r.parameters.scheduleTask,
                      action: "create",
                    });
                    // 更新任务栏信息
                    // 通知父组件更新
                    this.$emit("handleClick");
                    this.$message.success("添加成功");
                  } else {
                    this.$message.error({
                      type: "error",
                      message: r.initMessage || "数据请求失败",
                    });
                  }
                })
                .catch((e) => {
                  this.$message.error({
                    type: "error",
                    message: e || "提交失败",
                  });
                });
            }
          } else {
            this.$message({
              type: "warning",
              message: "请选择起止时间!",
            });
            return false;
          }
        } else {
          return false;
        }
      });
    },
    // 点击取消
    fCancel() {
      this.scheduleVisible = false;
      this.$emit("fCancel", false);
    },
    // 上传附件
    uploadSuccess(attachment) {
      if (this.form.scheduleId == null) {
        this.form.attachmentIds =
          (this.form.attachmentIds || "") + `,${attachment.attachmentId}`;
      }
    },
    // 关联业务
    selectdataTy(val) {
      this.form.dataKey = null;
      request({
        url: "/admin/scheduleTask/getDataOptions",
        method: "get",
        params: {
          dataType: val,
        },
      })
        .then((r) => {
          if (r && !r.initMessage) {
            this.contractOptions = r.parameters.dataOptions;
          } else {
            this.$message.error(r.initMessage || "数据请求失败");
          }
        })
        .catch((e) => {
          this.$message.error(e);
        });
    },
    remoteContract(query) {
      if (query !== "") {
        this.contractLoading = true;
        setTimeout(() => {
          this.contractLoading = false;
          this.contractOptions = this.contractOptions.filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.contractOptions = [];
      }
    },
    // 删除负责人员
    removeDomain(item) {
      var index = this.functionary.indexOf(item);
      if (index !== -1) {
        this.functionary.splice(index, 1);
      }
    },
    // 添加负责人员
    addDomain() {
      this.functionary.push({
        userType: null,
        userName: [],
        key: Date.now(),
      });
    },
    //弹窗关闭
    scheduleclose(type) {
      this.functionary = [
        {
          userType: null,
          userName: [],
        },
      ];
      this.operTimes = [];
      this.repeatWeek = [];
      //置空数据，清除校验
      this.$refs["form"].resetFields();
      this.form = _.extend({}, this.model);
      if (type !== "change") this.$emit("scheduleclose", false);
    },
  },
};
</script>

<style lang="less" scoped>
// 标题
.titleZise {
  display: flex;
  flex-direction: column;
  border-bottom: 1px solid #e7ecf0;
  & > div:nth-child(1) {
    text-align: center;
    font-weight: bold;
    font-size: 22px;
    padding: 20px 0;
  }
  & > div:nth-child(2) {
    padding-bottom: 10px;
  }
}

// 内容
.el-form {
  padding-right: 60px;
  margin-left: -10px;
}
.el-dialog__wrapper /deep/ .el-dialog__body {
  padding-top: 10px;
}
</style>